'use strict';
const BaseService = require('./base');
const modelName = 'User'
class UserService extends BaseService {
    constructor(ctx) {
        super(ctx, modelName);
    }
    async login(data) {
        const { ctx } = this;
        const { username, password } = data;
        const user = await ctx.model.User.findOne({
            where: {
                username,
                password,
            }
        });
        if (!user) {
            throw new Error('用户名或密码错误');
        }
        if (user.status === 0) {
            throw new Error('用户已被禁用');
        }
        return user;
    }
    async addMoney(data) {
        // 查找任务
        const { ctx } = this;
        /**
         *
         *             user_id: taskRecord.dataValues.user_id,
         *             price: taskRecord.dataValues.price,
         *             task_id:taskRecord.dataValues.task_id,
         *             task_record_id:taskRecord.dataValues.id,
         *             desc: '任务完成奖励'
         */
        const { user_id, price,task_id,task_record_id, desc } = data;
        let type = 1
        // 用户
        const user = await ctx.model.User.findOne({
            where: {
                id: user_id,
                status: 1,
            }
        });
        if (!user) {
            throw new Error('用户不存在');
        }
        await ctx.service.balance.create({
            user_id,
            amount: price,
            type,
            task_id,
            task_record_id,
            desc
        })
        // 充值
        return this.ctx.model.User.update({
            balance: parseFloat(user.balance) + parseFloat(price)
        }, {
            where: {
                id: user_id
            }
        });
    }
}
module.exports = UserService;
